package com.scpii.universal.dispatch.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import com.google.protobuf.InvalidProtocolBufferException;
import com.scpii.universal.dispatch.Const;
import com.scpii.universal.dispatch.Const.DispathConfig;
import com.scpii.universal.dispatch.Const.IniConfig;
import com.scpii.universal.dispatch.domain.CompileTask;
import com.scpii.universal.dispatch.persistence.CompileTaskMapper;
import com.scpii.universal.dispatch.service.CompileTaskService;
import com.scpii.universal.pb.UniversalProtocol.Cmd;
import com.scpii.universal.pb.UniversalProtocol.CreatComplieTaskSC;
import com.scpii.universal.pb.UniversalProtocol.FinishComplieTask;
import com.scpii.universal.pb.UniversalProtocol.GetPackInfoCS;
import com.scpii.universal.pb.UniversalProtocol.GetPackInfoSC;
import com.scpii.universal.pb.UniversalProtocol.GetTaskSC;
import com.scpii.universal.pb.UniversalProtocol.QryFinishComplieTaskSC;
import com.scpii.universal.pb.UniversalProtocol.TaskSC;
import com.scpii.universal.util.Conversion;

@Service
@Transactional
public class CompileTaskServiceImpl implements CompileTaskService {
	private static final Logger log = LoggerFactory
			.getLogger(CompileTaskServiceImpl.class);

	@Resource
	private CompileTaskMapper compileTaskMapper;

	@Resource
	private RestTemplate restTemplate;

	@Override
	public List<CompileTask> getTask(Integer statuss) {
		CompileTask qryRecord = new CompileTask();
		qryRecord.setStatus(statuss);
		List<CompileTask> rs = compileTaskMapper.selectBySelective(qryRecord);
		return rs;
	}

	@Override
	public List<CompileTask> getTaskByAppUpdateId(Integer appUpdateId) {
		CompileTask qryRecord = new CompileTask();
		qryRecord.setAppUpdateId(appUpdateId);
		List<CompileTask> rs = compileTaskMapper.selectBySelective(qryRecord);
		return rs;
	}

	@Override
	public byte[] getTaskByAppUpdateIdAsPb(Integer appUpdateId) {
		List<CompileTask> tasks = getTaskByAppUpdateId(appUpdateId);
		QryFinishComplieTaskSC.Builder builder = QryFinishComplieTaskSC
				.newBuilder();
		for (CompileTask task : tasks) {
			FinishComplieTask.Builder builderItem = FinishComplieTask
					.newBuilder();
			builderItem.setAppUpdateId(task.getAppUpdateId().intValue());
			builderItem.setConfigName(task.getConfigName() == null ? "" : task
					.getConfigName());
			builderItem.setUrl(task.getUrl() == null ? "" : task.getUrl());
			builder.addFinishComplieTask(builderItem);
		}
		return builder.build().toByteArray();
	}

	@Override
	public List<CompileTask> getWaitCompileTask() {
		CompileTask qryRecord = new CompileTask();
		qryRecord.setStatus(Const.COMPLETE_PACK_STATE);
		List<CompileTask> rs = compileTaskMapper.selectBySelective(qryRecord);
		return rs;
	}

	@Override
	public List<CompileTask> getWaitCompileTask(Integer appOSType) {
		CompileTask qryRecord = new CompileTask();
		qryRecord.setStatus(Const.COMPLETE_PACK_STATE);
		qryRecord.setAppOSType(appOSType);
		List<CompileTask> rs = compileTaskMapper.selectBySelective(qryRecord);
		return rs;
	}

	public byte[] getWaitCompileTaskAsPb(Integer intAppOsType) {
		List<CompileTask> tasks = getWaitCompileTask(intAppOsType);
		log.info("系统类型为" + intAppOsType + "任务数为:" + tasks.size());
		GetTaskSC.Builder builder = GetTaskSC.newBuilder();
		for (CompileTask task : tasks) {
			TaskSC.Builder builderItem = TaskSC.newBuilder();
			builderItem.setAppName(task.getAppName());
			builderItem.setTaskID(task.getCompileTaskId().intValue());
			builderItem.setConfigName(task.getConfigName() == null ? "" : task
					.getConfigName());
			builderItem.setAppSign(task.getAppSign());
			builderItem.setStyleId(task.getStyleId());
			builder.addItem(builderItem);
			log.info("appName:" + task.getAppName() + "/taskID:"
					+ task.getCompileTaskId().intValue() + "/configName:"
					+ task.getConfigName() + "/appsin:" + task.getAppSign()
					+ "/style:" + task.getStyleId());
		}
		return builder.build().toByteArray();
	}

	@Override
	public void updateCompleteCompileTask(Integer taskId, String fileUrl) {
		CompileTask record = new CompileTask();
		record.setCompileTaskId(taskId);
		record.setTaskEndTime(new Date());
		record.setStatus(Const.COMPLETE_COMPILE_STATE);
		record.setUrl(fileUrl);
		compileTaskMapper.updateByPrimaryKeySelective(record);
	}

	public void updateCompleteCompileTaskBatch(List<CompileTask> tasks) {
		for (CompileTask task : tasks) {
			task.setTaskEndTime(new Date());
			task.setStatus(Const.COMPLETE_COMPILE_STATE);
			compileTaskMapper.updateByPrimaryKeySelective(task);
		}
	}

	@Override
	public byte[] creatComplieTask(Integer intCompileTaskId,
			Integer intAppUpdateId, Integer intAppOsType, String varAppSign,
			String varAppName, String appVersion, Integer intSytleId) {
		CompileTask saveRecord = new CompileTask();
		saveRecord.setCompileTaskId(intCompileTaskId);
		saveRecord.setAppUpdateId(intAppUpdateId);
		saveRecord.setAppOSType(intAppOsType);
		saveRecord.setAppSign(varAppSign);
		saveRecord.setAppName(varAppName);
		saveRecord.setStatus(Const.WAIT_PACK_STATE);
		saveRecord.setTaskStartTime(new Date());
		saveRecord.setConfigName(IniConfig.SYS_SIGN + intAppUpdateId + "_"
				+ appVersion);
		saveRecord.setStyleId(intSytleId);
		compileTaskMapper.insert(saveRecord);
		CreatComplieTaskSC.Builder builder = CreatComplieTaskSC.newBuilder();
		builder.setOpCode(Const.OP_CODE_SUCESS);
		return builder.build().toByteArray();
	}

	@Override
	public List<CompileTask> qryFinishComplieTask() {
		CompileTask qryRecord = new CompileTask();
		qryRecord.setStatus(Const.COMPLETE_COMPILE_STATE);
		List<CompileTask> rs = compileTaskMapper.selectBySelective(qryRecord);
		return rs;
	}

	public byte[] qryFinishComplieTaskAsPb() {
		List<CompileTask> tasks = qryFinishComplieTask();
		QryFinishComplieTaskSC.Builder builder = QryFinishComplieTaskSC
				.newBuilder();
		for (CompileTask task : tasks) {
			FinishComplieTask.Builder builderItem = FinishComplieTask
					.newBuilder();
			builderItem.setAppUpdateId(task.getAppUpdateId().intValue());
			builderItem.setConfigName(task.getConfigName());
			builder.addFinishComplieTask(builderItem);
		}
		return builder.build().toByteArray();
	}

	@Override
	public GetPackInfoSC getPackInfo(Integer intAppUpdateId)
			throws InvalidProtocolBufferException {
		log.info("获取打包信息开始");
		GetPackInfoCS.Builder builder = GetPackInfoCS.newBuilder();
		builder.setAppUpdateId(intAppUpdateId.intValue());
		GetPackInfoCS cs = builder.build();
		byte[] buffer = cs.toByteArray();
		String reqStr = Conversion.bytesToHexString(buffer);
		String url = DispathConfig.SERVER_HOST + "rest?cmd="
				+ Cmd.GetPackInfo.getNumber() + "&data=" + reqStr;
		byte[] resData = restTemplate.getForObject(url, byte[].class);
		log.info("resData:" + resData);
		GetPackInfoSC sc = GetPackInfoSC.parseFrom(resData);
		log.info("获取打包信息结束");
		return sc;
	}

	@Override
	public void updateCompletePackTask(Integer taskId) {
		CompileTask record = new CompileTask();
		record.setCompileTaskId(taskId);
		record.setPackTime(new Date());
		record.setStatus(Const.COMPLETE_PACK_STATE);
		compileTaskMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public void updateCompileTaskFaile(Integer taskId, String erroMsg) {
		CompileTask record = new CompileTask();
		record.setCompileTaskId(taskId);
		record.setPackTime(new Date());
		record.setStatus(Const.COMPILE_ERRO);
		record.setErroInfo(erroMsg);
		compileTaskMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public int getSeq() {
		return compileTaskMapper.getSeq();
	}
}